/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cifar10.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 *
 * @author mwh
 */
public class Alphabet {

    Map<String, Integer> alphabet;
    Map<Integer,String> biAlphabet;

    int nextIndex;
    boolean allowGrowth;

    public Alphabet() {
        alphabet = new HashMap<String, Integer>();
        biAlphabet = new HashMap<Integer, String>();
        nextIndex = 1;
        allowGrowth = true;
    }

    public int lookup(String fn) {
        Integer index = alphabet.get(fn);
        if (index == null) {
            if (allowGrowth) {
                index = nextIndex;
                nextIndex++;
                alphabet.put(fn, index);
                biAlphabet.put(index, fn);
            } else {
                return -1;
            }
        }
        return index;
    }

    public String getName(int index) {
        return biAlphabet.get(index);
    }
    
    public void setAllowGrowth(boolean allowGrowth) {
        this.allowGrowth = allowGrowth;
    }
    
    public void save(String fn) throws IOException{
        PrintWriter out = new PrintWriter(fn);
        for (Entry<String,Integer> e : alphabet.entrySet()) {
            out.println(e.getKey() + "\t" + e.getValue());
        }
        out.close();
    }
    
    public void load(String fn) throws IOException {
        alphabet = new HashMap<String, Integer>();
        biAlphabet = new HashMap<Integer, String>();
        int maxIndex = -1;
        BufferedReader reader = new BufferedReader(new FileReader(fn));
        String line;
        while ((line = reader.readLine()) != null) {
            String[] fields = line.split("\t");
            String featname = fields[0];
            int index = Integer.parseInt(fields[1]);
            alphabet.put(featname, index);
            biAlphabet.put(index, featname);
            maxIndex = Math.max(maxIndex,index);
        }
        reader.close();
        nextIndex = maxIndex +1;
    }

}
